$(function() {
  var $captchaImage = $('#captchaImage');
  var $rememberMe = $('#rememberMe');
  var $username = $('#username');
  var $password = $('#password');
  var cookieName = 'ad-web.username';
  var $captcha = $('#captcha');

  // 记住用户名
  if (getCookie(cookieName) != null) {
    $rememberMe.prop('checked', true);
    $username.val(getCookie(cookieName));
    $password.focus();
  } else {
    $rememberMe.prop('checked', false);
    $username.focus();
  }
  // 更换验证码
  $captchaImage.click(function() {
    $captchaImage.attr(
      'src',
      xinyunlian.base + '/captcha.jhtml?timestamp=' + new Date().valueOf()
    );
  });

  $(document).keydown(function(event) {
    if (event.keyCode == 13) {
      $('#login').click();
    }
  });

  $('#login').on('click', function() {
    if ($rememberMe.prop('checked')) {
      addCookie(cookieName, $username.val(), { expires: 7 * 24 * 60 * 60 });
    } else {
      removeCookie(cookieName);
    }

    $('#error-word').html('');

    var username = $.trim($username.val());
    var password = $.trim($password.val());
    var captchaCode = $.trim($captcha.val());
    var message = '';

    if (!username) {
      message = '用户名不能为空!';
    } else if (!password) {
      message = '密码不能为空!';
    } else if (!captchaCode) {
      message = '验证码不能为空!';
    }

    if (!!message) {
      errorWindow('#error-word', message);
      return false;
    } else {
      $.ajax({
        url: xinyunlian.base + '/login/login.jhtml',
        type: 'post',
        dataType: 'json',
        data: {
          username: username,
          password: md5(password),
          captcha: captchaCode
        },
        cache: false,
        async: false,
        success: function(message) {
          if (message) {
            errorWindow('#error-word', message);
            $captchaImage.click();
            return false;
          } else {
            window.location.href = '/index.html';
          }
        }
      });
    }
  });

  function errorWindow(eclass, word) {
    $(eclass).html('※ ' + word);
  }
});
